package com.system.travel.common.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码工具类
 *
 * @author lucas
 * @date 2024/01/01
 */
public class CaptchaUtils {

    private static final String CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;

    /**
     * 生成验证码
     */
    public static String generateCaptchaCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            code.append(CODES.charAt(random.nextInt(CODES.length())));
        }
        return code.toString();
    }

    /**
     * 生成验证码图片
     */
    public static BufferedImage generateCaptchaImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        
        // 设置背景色
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 绘制干扰线
        Random random = new Random();
        g2.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g2.drawLine(x1, y1, x2, y2);
        }
        
        // 绘制验证码
        g2.setColor(Color.BLACK);
        g2.setFont(new Font("Arial", Font.BOLD, 28));
        for (int i = 0; i < code.length(); i++) {
            g2.drawString(String.valueOf(code.charAt(i)), 20 + i * 20, 30);
        }
        
        g2.dispose();
        return image;
    }
} 